package com.snut.viruscheck.controller;

import com.alibaba.cola.dto.Response;
import com.alibaba.fastjson.JSONObject;
import com.snut.viruscheck.service.LoginService;
import com.snut.viruscheck.satoken.login.dto.LoginQry;
import com.snut.viruscheck.entity.TbTempEntity;
import com.snut.viruscheck.entity.dto.ExcelTemp;
import com.snut.viruscheck.service.baseService;
import com.snut.viruscheck.tokenUtils.annotation.IdempotentBarrier;
import com.snut.viruscheck.tokenUtils.enums.IdempotentType;
import com.snut.viruscheck.tokenUtils.util.RedisIdempotentUtils;
import com.snut.viruscheck.utils.Excel.ExcelUtils;
import com.snut.viruscheck.utils.address.AddressUtils;
import com.snut.viruscheck.utils.address.IpUtils;
import com.snut.viruscheck.utils.entity.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;
//@ResponseBody
@Controller
public class RestController {

    private static final Logger log = LoggerFactory.getLogger(RestController.class);

    @Autowired
    baseService baseService;

    @Autowired
    RedisIdempotentUtils redisIdempotentUtils ;


    @Autowired
    LoginService loginService;

    @GetMapping({"/","/login-2"})
    public String getIndex(){
        return "login-2";
    }

    @GetMapping({"/IndexPage.html","IndexPage","IndexPage.html"})
    public String IndexPage(){
        return "IndexPage";
    }


    @RequestMapping(value = "/adminManage")

    public String adminManage() {
        return "admin";
    }
//
//
    @PostMapping("/login")
    @ResponseBody
    public Response login(@RequestBody LoginQry loginQry) {
        return loginService.login(loginQry);
    }
//
//    @SaCheckLogin
//    @GetMapping("/check_login")
//    @ResponseBody
//    public Response checkLogin(){
//        log.debug("登录用户id:{}", StpUtil.getLoginIdAsLong());
//        log.debug("token：{}",StpUtil.getTokenInfo().toString());
//        return Response.buildSuccess();
//    }
//
//    @SaCheckRole("admin")
//    @GetMapping("/check_role")
//    @ResponseBody
//    public Response checkRole(){
//        log.debug("登录用户id:{}",StpUtil.getLoginIdAsLong());
//        log.debug("token：{}",StpUtil.getTokenInfo().toString());
//        return Response.buildSuccess();
//    }
//
//    @SaCheckPermission("role:add")
//    @GetMapping("/check_permission")
//    @ResponseBody
//    public Response checkPermission(){
//        log.debug("登录用户id:{}",StpUtil.getLoginIdAsLong());
//        log.debug("token：{}",StpUtil.getTokenInfo().toString());
//        return Response.buildSuccess();
//    }
//
//    @GetMapping("/logout")
//    @ResponseBody
//    public Response logout(){
//        log.debug("退出登录");
//        StpUtil.logout();
//        return Response.buildSuccess();
//    }
//
//    @GetMapping({"/","login","login.html"})
//    public String loginPage(){
//        return "/login";
//    }






    @RequestMapping(value="/locate")
    public String getLocate(HttpServletRequest httpRequest) throws UnsupportedEncodingException {

    String ip= IpUtils.getIpAddr (httpRequest);
        System.out.println (ip);
        String returnStr =  AddressUtils.getAddresses ("ip="+ip,"UTF-8");
        System.out.println (returnStr);
        return returnStr;
    }
    /**
     * token获取和校验
     */
    @RequestMapping("/idempotentGenerator")
    @CrossOrigin
    @ResponseBody
    public String IdempotentGenerator() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = attributes.getRequest();

        //        log.info (idempotent);
//        request.setAttribute("token", idempotent);
        return redisIdempotentUtils.getIdempotent ();
    }

    // 验证Idempotent
//    @RequestMapping(value = "/addIdempotent", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @CrossOrigin
//    @IdempotentBarrier(value = IdempotentType.IDEMPOTENT_HEAD)
//
//    @ResponseBody
//    public String AddIdempotent(@RequestBody  TbTempEntity tbTempEntity) {
////        log.info (order.toString ());
////        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
////        HttpServletRequest request = attributes.getRequest();
////        String token=request.getHeader("token");
//        return "success";
//
//    }

    /**
     * 更新当日统计信息
     *
//     * @param info
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/updateInfo", method = RequestMethod.POST)
    @CrossOrigin
    @IdempotentBarrier(value = IdempotentType.IDEMPOTENT_HEAD)
//    @IdempotentBarrier(value = IdempotentType.IDEMPOTENT_HEAD)
    //导入后不知道怎么搞，把验证的token放在头还是参数里
    public String updateInfo(@RequestBody String tbTempEntity) throws ParseException {
        //解析前端JSON
        JSONObject jsonObject = JSONObject.parseObject (tbTempEntity);
        int id = jsonObject.getIntValue ("id");
        String temperature = jsonObject.getString ("temperature");
        String des = jsonObject.getString ("des");
        String address = jsonObject.getString ("address");
        //根据学号查询Student对象
        Object student = baseService.getStudent (id);
        if (student != null) {
            //生成当前日期yyyy-MM-dd
            java.util.Date curDate = new java.util.Date ();
            java.sql.Date date = new java.sql.Date (curDate.getTime ());
            TbTempEntity tempEntity = new TbTempEntity ();
            //构建表对象实体
            tempEntity.setTemperature (temperature);
            tempEntity.setDesc (des);
            tempEntity.setAddress (address);
            tempEntity.setSysDate (date);
            tempEntity.setStudentId (id);
            try {
                //更新数据库表
                baseService.updateTemp (tempEntity);
                return "IndexPage";
            } catch (Exception e) {
                System.out.println (e);
            }
        }
        return "";
    }

    //2020-02-17 13:00:37.196 TRACE 13068 --- [nio-8080-exec-3] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [DATE] - [2020-02-16]

    /**
     * 查询结果统计结果
     *
     * @param day      yyyy-MM-dd
     * @param response response
     * @param request  request
     * @throws IOException io异常
     */
    @RequestMapping(value = "/selectTempByDay", method = RequestMethod.POST)
    public void selectTempByDay(@RequestBody String day,
                                HttpServletResponse response,
                                HttpServletRequest request

    ) throws IOException {
        JSONObject jsonObject = JSONObject.parseObject (day);
        String strDay = jsonObject.getString ("day");
//        java.util.Date curDate = new java.util.Date();
//        java.sql.Date date2 = new java.sql.Date(curDate.getTime());
//        date2.setDate(16);
        //解析JSON
        java.sql.Date date = ExcelUtils.strToDate (strDay);


//        Calendar calendar =new GregorianCalendar();
//        calendar.setTime(date);
//        calendar.add (calendar.DATE,-1);
//
//        java.util.Date utilDate = (java.util.Date)calendar.getTime();
//    //java.util.Date日期转换成转成java.sql.Date格式
//        java.sql.Date newDate1 =new java.sql.Date (utilDate.getTime());
//
//
//        long now=date.getTime ();
//        java.sql.Date newDate=new java.sql.Date (now-86400000);
//        System.out.println (newDate1);
//        date.
        //获取表实体ExcelTemp
        List<Object[]> temps = baseService.selectTempByDay (date);
        //使用工具类原生sql结果集->实体转换
        List<ExcelTemp> tempList = EntityUtils.castEntity (temps, ExcelTemp.class, new ExcelTemp ());
        //根据StudentId去重 JAVA8新特性
        List<ExcelTemp> newList = tempList.stream ().collect (Collectors.collectingAndThen (Collectors.toCollection (() -> new TreeSet<> (Comparator.comparing (ExcelTemp::getStudentId))), ArrayList::new));
        for (ExcelTemp e : newList) {
            if (e.getDes ().equals ("")) {
                e.setDes ("无");
            }
        }
        //使用工具类创建Excel文件
        ExcelUtils.createExcel (newList, "网安18软件1班-" + strDay, response, request, strDay);
    }
}
